const PizZip = require('pizzip');
const Docxtemplater = require('docxtemplater');
const fs = require('fs');
const ImageModule = require('docxtemplater-image-module-free');
const sizeOf = require('image-size');
const dayjs = require('dayjs');
const download = require('download');

const config = require('../../userConfig.json');

let imgCount = 0;

const saveAsDoc = blogList => {
  const docTemplate = fs.readFileSync('./blog_template.docx', 'binary');
  const zip = new PizZip(docTemplate);

  const imageOptions = {
    centered: false,
    getImage: tagValue => {
      const path = './dist/' + tagValue.split('/').pop();

      return new Promise((resolve, reject) => {
        fs.readFile(path, (err, data) => {
          imgCount++;

          if (err) {
            // 本地没有,从远程下载
            download(tagValue, './dist', {
              timeout: {
                lookup: 10000,
                connect: 10000,
                secureConnect: 10000,
                socket: 10000,
                send: 10000,
                response: 20000
              }
            })
              .then(res => {
                resolve(res);
              })
              .catch(() => {
                reject(err);
              });
          } else {
            console.log(`第${imgCount}张图片获取失败了,请手动复制以下链接到浏览器中查看`);
            console.log(tagValue);
            resolve(data);
          }
        });
      });
    },
    getSize(img) {
      console.log(`已成功获取到第${imgCount}张图片,正在设置宽高`);

      const { width, height } = sizeOf(img);
      const forceHeight = 126;
      const ratio = forceHeight / height;
      return [Math.round(width * ratio), forceHeight];
    }
  };

  const imgModule = new ImageModule(imageOptions);

  const docOptions = {
    paragraphLoop: true,
    linebreaks: true,
    modules: [imgModule]
  };

  const doc = new Docxtemplater(zip, docOptions);

  doc
    .renderAsync({ blogList })
    .then(res => {
      console.log('渲染数据成功,开始生成doc文件');

      const buf = doc.getZip().generate({
        type: 'nodebuffer',
        // compression: DEFLATE adds a compression step.
        // For a 50MB output document, expect 500ms additional CPU time
        compression: 'DEFLATE'
      });
      const name = `${config.blogName}微博-${dayjs().format('MM-DD HH:mm')}`;

      fs.writeFileSync(`./${name}.docx`, buf);
    })
    .catch(err => {
      console.log('异步渲染doc出错了', err);
    });
};

module.exports = saveAsDoc;
